package com.cicadamob.contact.api.Utils.pinyin;

import android.text.TextUtils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinTools {
	
	public static final String PY="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	
	/**
	 * 返回相应的字母的下标，如A 1,B 2
	 * @param src
	 * @return
	 */
	public static int getIndex4Pinyin(String src) {
		return PY.indexOf(src.toUpperCase())+1;
	}

    /**
     * 
     * 将字符串转换成拼音数组
     * 
     * 
     * 
     * @param src
     * 
     * @return
     */

    public static String[] stringToPinyin(String src)
    {

        return stringToPinyin(src, false, null);

    }

    /**
     * 
     * 将字符串转换成拼音数组
     * 
     * 
     * 
     * @param src
     * 
     * @return
     */

    public static String[] stringToPinyin(String src, String separator)
    {

        return stringToPinyin(src, true, separator);

    }

    /**
     * 
     * 将字符串转换成拼音数组
     * 
     * 
     * 
     * @param src
     * 
     * @param isPolyphone
     * 
     *            是否查出多音字的所有拼音
     * 
     * @param separator
     * 
     *            多音字拼音之间的分隔符
     * 
     * @return
     */

    public static String[] stringToPinyin(String src, boolean isPolyphone,

    String separator)
    {

        // 判断字符串是否为空

        if ("".equals(src) || null == src)
        {

            return null;

        }

        char[] srcChar = src.toCharArray();

        int srcCount = srcChar.length;

        String[] srcStr = new String[srcCount];

        for (int i = 0; i < srcCount; i++)
        {
            srcStr[i] = charToPinyin(srcChar[i], isPolyphone, separator);
        }

        return srcStr;

    }

    /**
     * 
     * 将单个字符转换成拼音
     * 
     * 
     * 
     * @param src
     * 
     * @return
     */

    public static String charToPinyin(char src, boolean isPolyphone,

    String separator)
    {

        // 创建汉语拼音处理类

        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();

        // 输出设置，大小写，音标方式

        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);

        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        StringBuffer tempPinying = new StringBuffer();

        // 如果是中文

        if (src > 128 && isChinese(src))
        {

            try
            {

                // 转换得出结果

                String[] strs = PinyinHelper.toHanyuPinyinStringArray(src,

                defaultFormat);

                // 是否查出多音字，默认是查出多音字的第一个字符

                if (isPolyphone && null != separator)
                {

                    for (int i = 0; i < strs.length; i++)
                    {

                        tempPinying.append(strs[i]);

                        if (strs.length != (i + 1))
                        {

                            // 多音字之间用特殊符号间隔起来

                            tempPinying.append(separator);

                        }

                    }

                } else if(strs!= null)
                {
                	if(strs.length>=0){

                    tempPinying.append(strs[0]);
                	}
                }

            } catch (BadHanyuPinyinOutputFormatCombination e)
            {

                e.printStackTrace();

            }

        } else
        {

            tempPinying.append(src);

        }

        return tempPinying.toString();

    }
    
    /**
     * 中文不包含 标点符号
     * @param c
     * @return
     */
    private static boolean isChinese(char c)
    {

        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);

        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS

//        || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS

//        || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A

//        || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B

//        || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION

//        || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS

//        || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
        )
        {

            return true;

        }

        return false;

    }


    /**
     * 
     * 将字符串数组转换成字符串
     * 
     * @param str
     * 
     * @param separator
     *            各个字符串之间的分隔符
     * 
     * @return
     */

    public static String stringArrayToString(String[] str, String separator)
    {

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < str.length; i++)
        {

            sb.append(str[i]);

            if (str.length != (i + 1))
            {

                sb.append(separator);

            }

        }

        return sb.toString();

    }

    /**
     * 
     * 简单的将各个字符数组之间连接起来
     * 
     * @param str
     * 
     * @return
     */

    public static String stringArrayToString(String[] str)
    {

        return stringArrayToString(str, "").replaceAll("u:", "v");

    }

    /**
     * 
     * 将字符数组转换成字符串
     * 
     * @param str
     * 
     * @param separator
     *            各个字符串之间的分隔符
     * 
     * @return
     */

    public static String charArrayToString(char[] ch, String separator)
    {

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < ch.length; i++)
        {

            sb.append(ch[i]);

            if (ch.length != (i + 1))
            {

                sb.append(separator);

            }

        }

        return sb.toString();

    }

    /**
     * 
     * 将字符数组转换成字符串
     * 
     * @param str
     * 
     * @return
     */

    public static String charArrayToString(char[] ch)
    {

        return charArrayToString(ch, " ");

    }

	public static String getHeadByStringArray(String[] str) {

		if(null==str){
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for(String strObj : str){
			if(strObj!=null){
				if(!TextUtils.isEmpty(strObj)){
					sb.append(strObj.charAt(0));
				}
			}
		}
		return sb.toString();

	}

	/**
	 * 
	 * 取汉字的首字母
	 * 
	 * @param src
	 * 
	 * @param isCapital
	 *            是否是大写
	 * 
	 * @return
	 */

    public static char[] getHeadByChar(char src, boolean isCapital)
    {

        // 如果不是汉字直接返回

        if (src <= 128)
        {
            return new char[] { src };
        }

        // 获取所有的拼音

        String[] pinyingStr = PinyinHelper.toHanyuPinyinStringArray(src);

        // 创建返回对象

        if (null != pinyingStr)
        {

            int polyphoneSize = pinyingStr.length;

            char[] headChars = new char[polyphoneSize];

            int i = 0;

            // 截取首字符

            for (String s : pinyingStr)
            {

                char headChar = s.charAt(0);

                // 首字母是否大写，默认是小写

                if (isCapital)
                {

                    headChars[i] = Character.toUpperCase(headChar);

                } else
                {

                    headChars[i] = headChar;

                }

                i++;
            }

            return headChars;
        } else
        {
            return new char[] { src };
        }
    }

    /**
     * 
     * 取汉字的首字母(默认是大写)
     * 
     * @param src
     * 
     * @return
     */

    public static char[] getHeadByChar(char src)
    {

        return getHeadByChar(src, true);

    }

    /**
     * 
     * 查找字符串首字母
     * 
     * @param src
     * 
     * @return
     */

    public static String[] getHeadByString(String src)
    {

        return getHeadByString(src, true);

    }

    /**
     * 
     * 查找字符串首字母
     * 
     * @param src
     * 
     * @param isCapital
     *            是否大写
     * 
     * @return
     */

    public static String[] getHeadByString(String src, boolean isCapital)
    {

        return getHeadByString(src, isCapital, null);

    }

    /**
     * 
     * 查找字符串首字母
     * 
     * @param src
     * 
     * @param isCapital
     *            是否大写
     * 
     * @param separator
     *            分隔符
     * 
     * @return
     */

    public static String[] getHeadByString(String src, boolean isCapital,
            String separator)
    {

        char[] chars = src.toCharArray();

        String[] headString = new String[chars.length];

        int i = 0;

        for (char ch : chars)
        {

            char[] chs = getHeadByChar(ch, isCapital);

            StringBuffer sb = new StringBuffer();

            if (null != separator)
            {

                int j = 1;

                for (char ch1 : chs)
                {

                    sb.append(ch1);

                    if (j != chs.length)
                    {

                        sb.append(separator);

                    }

                    j++;

                }

            } else
            {

                sb.append(chs[0]);

            }

            headString[i] = sb.toString();

            i++;

        }

        return headString;

    }
    
    /**
     * 根据姓名获取相应的拼音然后转成对应的long
     * 规则：每个字母占5位，左对齐补0,最大允许12个字母。
     * @param src
     * @return
     */
    public static long stringToLong(String src){
        long value = 0L;
        if(null==src || "".equals(src.trim())){
            return value;
        }
        String pinyin = PinyinTools.stringArrayToString(PinyinTools.stringToPinyin(src));
        int pinyinLen = pinyin.length();
        for(int i=0;i<12;i++){
            if(i>0){
                value=value<<5;
            }
            if(i<pinyinLen){
                value+=Long.valueOf(PY.indexOf(pinyin.substring(i,i+1).toUpperCase())+1).longValue();
            }
            
        }
        
        return value;
    }
    
    /**获取全拼（大写）**/
    public static String getAllPinYin(String name){
    	String pinYin="";
    	name=name.trim();
    	if(isEmpty(name)){
    		return pinYin;
    	}
    	return  PinyinTools.stringArrayToString(PinyinTools.stringToPinyin(name)).toUpperCase(); 
    }
    /**获取首拼音（小写）**/
    public static String getShouPinYin(String name){
    	name=name.trim();
    	String pinYin="";
    	if(isEmpty(name)){
    		return pinYin;
    	}
    	
    	String[] pinyin = PinyinTools.stringToPinyin(name);
    	
    	return PinyinTools.getHeadByStringArray(pinyin).toLowerCase();
    }
    /**获取首拼音（大写）**/
    public static String getFirstCharPinYin(String name){
    	name=name.trim();
    	String pinYin="";
    	if(isEmpty(name)){
    		return pinYin;
    	}
    	
    	String[] pinyin = PinyinTools.stringToPinyin(name);
    	
    	return PinyinTools.getHeadByStringArray(pinyin).toUpperCase();
    }
    /**
     * 获取排序字段
     * @param name
     * @return
     */
    public static long getSort(String name){
    	long pinYinNumber=0;
    	if(isEmpty(name)){
    		return pinYinNumber;
    	}
    	pinYinNumber=PinyinTools.stringToLong(PinyinTools.stringArrayToString(PinyinTools.stringToPinyin(name)));
    	return pinYinNumber;
    }
    
    public static boolean isEmpty(String str) {
		if (str == null || str == "" || str.trim().equals("")
				|| str.trim().equalsIgnoreCase("null")
				|| str.trim().length() == 0)
			return true;
		else
			return false;
	}



}
